package com.chookss.tools;

import android.content.Context;
import android.os.Environment;

import com.johnrambo.ktea.ktExtends.ShareUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;

public class UUidUtils {
    private static final String UUID_FILE_DIR = "android.system.data/uuid/";
    private static final String UUID_FILE_NAME = "uuid_kt_tiktok.uuid";
    private static File uuidDir;
    public static String getCustomUUID(Context context,String ANDROID_ID) {
        String fileUUID = getUUIDByFile(context);
        boolean flag = !fileUUID.equals("");
        if (flag) {
        } else {
            creatUUIDFile(context,ANDROID_ID);
            fileUUID = getUUIDByFile(context);
        }
        return fileUUID;
    }
    /**
     * 在媒体文件中 生成fileName文件
     */
    public static void creatUUIDFile(Context context,String ANDROID_ID) {
        uuidDir = new File(Environment.getExternalStorageDirectory(), UUID_FILE_DIR);
        if (!uuidDir.exists()) {
            uuidDir.mkdirs();
        }
        File uuidFile = new File(uuidDir, UUID_FILE_NAME);
        //讲UUID写入到文件中
        if(Utils.isNull(ANDROID_ID)){
            //讲UUID写入到文件中
            String uuid= UUID.randomUUID().toString();
            writeStringTofile(uuidFile, uuid);
            new ShareUtils().putString(context, "local_id", uuid);
        }else{
            //讲UUID写入到文件中
            writeStringTofile(uuidFile, ANDROID_ID);
            new ShareUtils().putString(context, "local_id", ANDROID_ID);
        }
    }

    /**
     * 读取配置文件中的设备ID
     */
    public static String getUUIDByFile(Context context) {
        File file = new File(Environment.getExternalStorageDirectory(), UUID_FILE_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        File uuidFile = new File(file, UUID_FILE_NAME);
        String path = "";
        try {
            path = readFileString(uuidFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 读取文本文件
     */
    public static String readFileString(File file) throws IOException {
        InputStreamReader isr = new InputStreamReader(
                new FileInputStream(file), "UTF-8");
        StringBuilder sb = new StringBuilder();
        char[] buf = new char[4096];
        int len;
        try {
            while ((len = isr.read(buf)) != -1) {
                sb.append(buf, 0, len);
            }
        } finally {
            isr.close();
        }
        return sb.toString();
    }

    public static void writeStringTofile(File file, String str) {
        try {
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(str.getBytes());
            outStream.close();
        } catch (Exception e) {

            e.printStackTrace();

        }


    }
}
